﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Web.Mvc;
using Beeldbankmvc.Code;
using Beeldbankmvc.Models;
using MvcSiteMapProvider.Web;
using System.Collections.Specialized;
using System.Net;
using System.Text;
using System.Web.UI;

namespace Beeldbankmvc.Controllers
{
    [HandleErrorWithELMAH]
    public class HomeController : Controller
    {
        BeeldbankLinqDataContext beeldBankDB = new BeeldbankLinqDataContext();
        MediaObjectRepository mediaObjectRepository = new MediaObjectRepository();
        //
        // GET: /Home/

        // cache the search query for a day
        [OutputCache(Duration = (3600 * 24), VaryByParam = "*", VaryByCustom = "IsLoggedIn", Location = OutputCacheLocation.Server)]
        public ActionResult Index()
        {
            return View();
        }

        //
        // GET: /Home/SiteMap/
        public ActionResult SiteMap()
        {
            return View();
        }

        // Used to test redirect
        public ActionResult RedirectToGoogle(string id)
        {
            //return RedirectToAction("FullPage", new { id = "406562" , type = "show"});

            using (var client = new WebClient())
            {
                var fields = new NameValueCollection
                {
                    { "alttekst", "Dit is een alt tekst" },
                    { "onderschrift", "Dit is een onderschrift" }
                };
                byte[] result = client.UploadValues(
                    "http://localhost:1024/Home/TestImagePost",
                    fields
                );

                return Content(Encoding.ASCII.GetString(result));
                
                // TODO: do something with the result
                // if it is a JSON object deserialize it back to a model
            }
        }

        // Cache the detail image rendering for a day [caching on the server]
        // Browser caching for these images is set to a full day [caching on the browser]
        //
        // So it could take two days before a changed image preview is displayed.
        public ActionResult DisplayDetail(string id)
        {
            int mediaObjectId = 0;
            BEELDBANK_MEDIAOBJECT mediaObject = null;
            try
            {
                mediaObjectId = Utility.getIdFromTitle(id);
                mediaObject = mediaObjectRepository.FindOne(mediaObjectId);
            }
            catch
            {
            }

            // Prevent errors when specifying the wrong id for viewing
            if (mediaObject == null)
                return RedirectToAction("Index", "Search");

            // Check if a preview file exists, then return this image
            if (Beeldbankmvc.Helpers.Tools.getPreviewImage(mediaObject) != "")
            {
                Image thumbnail = Image.FromFile(Beeldbankmvc.Helpers.Tools.getPreviewImage(mediaObject));
                return new ImageResult { Image = thumbnail, ImageFormat = ImageFormat.Jpeg, cacheHeaderToNull = false };
            }
            else
                // Return the database thumbnail
                return DisplayThumb(mediaObjectId.ToString());
        }

        // Same controller but without caching, for edit pages
        public ActionResult DisplayDetailNoCache(string id)
        {
            MediaObjectRepository mediaObjectRepository = new MediaObjectRepository();

            int mediaObjectId = 0;
            BEELDBANK_MEDIAOBJECT mediaObject = null;
            try
            {
                mediaObjectId = Utility.getIdFromTitle(id);
                mediaObject = mediaObjectRepository.FindOne(mediaObjectId);
            }
            catch
            {
            }

            // Prevent errors when specifying the wrong id for viewing
            if (mediaObject == null)
                return RedirectToAction("Index", "Search");
            
            // Check if a preview file exists, then return this image
            if (Beeldbankmvc.Helpers.Tools.getPreviewImage(mediaObject) != "")
            {
                Image thumbnail = Image.FromFile(Beeldbankmvc.Helpers.Tools.getPreviewImage(mediaObject));
                return new ImageResult { Image = thumbnail, ImageFormat = ImageFormat.Jpeg, cacheHeaderToNull = true };
            }
            else
                // Return the database thumbnail
                return DisplayThumb(mediaObjectId.ToString());
        }

        // Cache the thumbnail rendering for a day [caching on the server]
        // Browser caching for these images is set to a full day [caching on the browser]
        //
        // So it could take two days before a changed image thumbnail is displayed.
        public ActionResult DisplayThumb(string id)
        {
            var thumbnailGallery = from p in beeldBankDB.BEELDBANK_MEDIAOBJECTs where p.Id == Convert.ToInt32(id) select p;

            if (thumbnailGallery.Count() > 0)
            {
                if (thumbnailGallery.Single().Thumbnail != null)
                {
                    Image thumbnail = null;

                    thumbnail = ImageHelper.BytesToImg((byte[])thumbnailGallery.Single().Thumbnail.ToArray());
                    return new ImageResult { Image = thumbnail, ImageFormat = ImageFormat.Jpeg, cacheHeaderToNull = false };
                }
            }

            Image noImage = Image.FromFile(Server.MapPath("/Content/Images/") + "noimage.jpg");

            return new ImageResult { Image = noImage, ImageFormat = ImageFormat.Jpeg };
        }

        // Same controller but without caching, for edit pages
        public ActionResult DisplayThumbNoCache(string id)
        {
            var thumbnailGallery = from p in beeldBankDB.BEELDBANK_MEDIAOBJECTs where p.Id == Convert.ToInt32(id) select p;

            if (thumbnailGallery.Count() > 0)
            {
                if (thumbnailGallery.Single().Thumbnail != null)
                {
                    Image thumbnail = null;

                    thumbnail = ImageHelper.BytesToImg((byte[])thumbnailGallery.Single().Thumbnail.ToArray());
                    return new ImageResult { Image = thumbnail, ImageFormat = ImageFormat.Jpeg, cacheHeaderToNull = true };
                }
            }

            Image noImage = Image.FromFile(Server.MapPath("/Content/Images/") + "noimage.jpg");

            return new ImageResult { Image = noImage, ImageFormat = ImageFormat.Jpeg };
        }

        // Added to improve access for Google search
        public ActionResult SiteMapXml()
        {
            return new XmlSiteMapResult();
        }

        public ActionResult Lost()
        {
            return View("Lost");
        }

        public ActionResult Error()
        {
            return View("Error");
        }

        public ActionResult WinApp()
        {
            return View();
        }

        public ActionResult WinApp_INTL()
        {
            return View();
        }

        [HttpPost]
        public void Rate(FormCollection collection)
        {
            StarRatingRepository StarRatingRep = new StarRatingRepository();

            int mediaObjectId = Convert.ToInt32(collection["mediaObjectId"]);

            // No filter on IP because companies can use one IP for location
            StarRatingRep.Add(collection["rate"], mediaObjectId, Request.ServerVariables["HTTP_X_FORWARDED_FOR"]);

            Response.Redirect(Request.UrlReferrer.AbsolutePath);
        }

        // unit test controler method
        public ActionResult Details(int Id)
        {
            return View("Details");
        } 

    }
}

